/*eslint-disable*/

import { get, post, del, setup, put } from '../utils/request';
import { isFunc } from '../utils/tools';
import store from '../store';
import route from '../router';
setup({
	baseURL: process.env.API_BASE_URL,
	// withCredentials: true,
	headers: {
		'content-type': 'application/json'
	},
	transformResponse: [
		function(data) {
			// 错误拦截
			if (!data) return {};
			const res = JSON.parse(data);
			if (res.status_code && res.status_code !== 200) {
				if (res.status_code === 401) {
					store.dispatch('toast', {
						type: 'warn',
						msg: '请重新登陆',
						code: res.status_code
					});
					route.replace('/login');
				} else {
					store.dispatch('toast', {
						type: 'warn',
						msg: res.message,
						code: res.status_code
					});
				}
				return Promise.reject(res);
			}
			return res;
		}
	],
	interceptors: {
		response(res) {
			const volidCode = [200, 201, 204];
			const code = res.status;
			if (process.env.NODE_ENV === 'development') {
				// console.log('res===============>', res);
			}
			if (volidCode.includes(code)) {
				return res.data;
			}
		},
		errorRep(err) {}
	}
});

const apis = {
	login: get('/api/user'),
};

/**
 * 通过接口名称返回请求对象
 * @param {string} entry
 */
const api = function(entry, data, params) {
	if (apis.hasOwnProperty(entry)) {
		return isFunc(apis[entry]) ? apis[entry](data, params) : apis[entry];
	}

	throw 'Entry not defined';
};
export default api;
